const mongoose = require('mongoose')
const bcrypt = require('bcrypt')

const environment = process.env.NODE_ENV
const stage = require('../config')[environment]

const Schema = mongoose.Schema

const userSchema = new Schema({
  username: {
    type: String,
    required: true,
    trim: true,
    unique: true
  },
  password: {
    type: String,
    required: true,
    trim: true,
    select: false
  },
  avatar: String,
  admin: Boolean,
  created_at: Date,
  updated_at: Date
})

// encrypt password before save
userSchema.pre('save', function (next) {
  const user = this
  if (!user.isModified || !user.isNew) {
    next()
  } else {
    user.admin = false
    const currentDate = new Date()
    user.updated_at = currentDate
    if (!user.created_at)
      user.created_at = currentDate
    bcrypt.hash(user.password, stage.saltingRounds, function (err, hash) {
      if (err) {
        console.log('Error hashing password for user', user.name)
        next(err)
      } else {
        user.password = hash
        next()
      }
    })
  }
})

module.exports = mongoose.model('User', userSchema)
